package com.eagle.epay.controller;

import com.eagle.epay.config.AlipayAccountConfig;
import com.eagle.epay.config.WxAccountConfig;
import com.eagle.epay.entity.PayInfo;
import com.eagle.epay.service.IPayService;
import com.lly835.bestpay.enums.BestPayResultEnum;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.exception.BestPayException;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.service.BestPayService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/pay")
@Slf4j
public class PayController {
	@Autowired
	private IPayService payService;

	@Autowired
	private WxAccountConfig wxAccountConfig;

	@Autowired
	private AlipayAccountConfig alipayAccountConfig;

	/**
	 * @param orderId
	 * @param amount
	 * @return
	 *
	 * 其他系统可以对接这个接口生成二维码
	 */
//	http://localhost:8080/pay/create?orderId=1234569810&amount=0.01&payType=ALIPAY_PC
//	http://eagle.natapp1.cc/pay/create?orderId=1578840622939&amount=0.01&payType=ALIPAY_PC
//	http://eagle.natapp1.cc/pay/create?orderId=1234569810&amount=0.01&payType=WXPAY_NATIVE
	@GetMapping("/create")
	public ModelAndView create(@RequestParam("orderId") String orderId,
							   @RequestParam("amount") BigDecimal amount,
							   @RequestParam("payType") BestPayTypeEnum bestPayTypeEnum){

		PayResponse resp = this.payService.create(orderId, amount,bestPayTypeEnum);
		if(bestPayTypeEnum == BestPayTypeEnum.WXPAY_NATIVE){
			Map resultMap = new HashMap<>();
			resultMap.put("code_url",resp.getCodeUrl());
			resultMap.put("orderId", orderId);
			resultMap.put("returnUrl", wxAccountConfig.getReturnUrl());
			ModelAndView view = new ModelAndView("wxNativePay",resultMap);
			return view;
		} else if(bestPayTypeEnum == BestPayTypeEnum.ALIPAY_PC){
			Map resultMap = new HashMap<>();
			resultMap.put("body",resp.getBody());
			ModelAndView view = new ModelAndView("alipayPcPay",resultMap);
			return view;
		}
		throw new BestPayException(BestPayResultEnum.PAY_TYPE_ERROR);

	}

	//一定是@ResponseBody,否则微信无法接收
	@PostMapping("/notify")
	@ResponseBody
	public String ansynNotify(@RequestBody String notifyData){

		return payService.asyncNotify(notifyData);
	}

	@GetMapping("/queryByOrderId")
	@ResponseBody
	public PayInfo queryByOrderId(@RequestParam String orderId) {
		return payService.queryByOrderId(orderId);
	}

}
